import type { RouteRecordRaw } from 'vue-router'
import type { LoginMenu } from '@/typings'
import router from '.'
import { useMenuStore, homeMenuPath } from '@/stores/menu'
import { staticMenus } from './static'
import { errorRoutes } from './error'
import { _ } from '@/utils'
import Layout from '@/layout/index.vue'

export const useDynamicRoute = () => {
  const menuStore = useMenuStore()
  const routeAllPathToCompMap = import.meta.glob(`../views/**/*.vue`)
  const homeRoute: RouteRecordRaw = {
    path: '/',
    name: 'Home',
    component: Layout,
    redirect: `/${homeMenuPath}`,
    children: []
  }

  const add = () => {
    router.addRoute(createDynamicRoute(menuStore.menus))
    errorRoutes.forEach((route: RouteRecordRaw) => {
      router.addRoute(route)
    })
  }

  const createDynamicRoute = (data: LoginMenu[]) => {
    //添加动态菜单
    homeRoute.children = createDynamicRouteList(data, '')

    //添加静态菜单
    homeRoute.children = homeRoute.children.concat(createStaticRouteList())

    return homeRoute
  }

  const createDynamicRouteList = (data: LoginMenu[], parentPath: string): RouteRecordRaw[] => {
    const menus: Array<RouteRecordRaw> = []

    data.forEach(ele => {
      const path = `${parentPath}${parentPath === '' ? '' : '/'}${ele.path}`
      if (ele.children && ele.children.length > 0) {
        const children = createDynamicRouteList(ele.children, path)
        children.forEach(child => {
          menus.push(child)
        })
      } else {
        menus.push(createComponent(ele, path))
        menuStore.setMenuIndex(ele)
      }
    })
    return menus
  }

  const createStaticRouteList = (): RouteRecordRaw[] => {
    const menus: Array<RouteRecordRaw> = []
    const compFuncKeys: { [key: string]: string[] } = {}

    //取出所有后台菜单中的权限Key集合，作为后面过程中判断的条件
    for (const menuId in menuStore.menuIndex) {
      const menu = menuStore.menuIndex[menuId]
      const path = getComponentPath(menu.component)
      compFuncKeys[path] = menu.funcKeys
    }

    staticMenus.forEach((ele: LoginMenu) => {
      //判断权限, 基于依赖属性, 比对从数据库查出的菜单按钮权限
      let auth = true
      if (ele.dependentAuth) {
        auth = false
        const compPath = getComponentPath(ele.dependentAuth.component)
        if (compFuncKeys[compPath]) {
          if (compFuncKeys[compPath].indexOf(ele.dependentAuth.funcKey) >= 0) {
            auth = true
          }
        }
      }
      if (auth) {
        menus.push(createComponent(ele, ele.path))
        menuStore.setMenuIndex(ele)
      }
    })
    return menus
  }

  const createComponent = (ele: LoginMenu, path: string) => {
    const underlinePath = path.replace(/([A-Z])/g, '-$1').toLowerCase()
    return {
      path: underlinePath,
      name: ele.menuId,
      component: routeAllPathToCompMap[`../views${getComponentPath(ele.component)}`],
      meta: {
        title: ele.menuName,
        funcKeys: ele.funcKeys,
        affix: ele.affix,
        noCache: ele.noCache,
        routeKey: underlinePath
      }
    }
  }

  const getComponentPath = (comp: string) => {
    return `/${_.lowerFirst(comp)}.vue`
  }

  return { add }
}
